<?php
namespace service\upload\local;

use service\upload\UploadInterface;
use think\facade\Db;
use think\facade\Filesystem;

class Upload implements UploadInterface
{
    private  $topic='';

    public function upload($files)
    {

        if(!$files)return_error(['info'=>'上传文件不能为空!']);
        $storage = Filesystem::disk('public');
        try {
            validate(['file'=>'filesize:15728640|fileExt:jpg,png,jpeg,webp,mp3'])
                ->check($files);
            $files = $files['file'];

            $data = [];
            
            if(is_array($files)){
                $url = [];
                foreach($files as $file) {
                    $fileDb = Db::name('file');
                    $temp['create_time']=date('Y-m-d H:i:s');
                    $temp['hash'] = $file->md5();
                    $urle = $fileDb->where(['hash'=>$temp['hash']])->value('url');

                    if($urle){
                        $url[]=$temp['url'] = $urle;
                    }else{
                        $url[]=$temp['url'] = '/storage/'.$storage->putFile($this->topic, $file);
                        $data[]=$temp;
                    }    
                }
                if(!empty($data)){
                    $fileDb->insertAll($data);
                }                
            }else{
                $fileDb = Db::name('file');
                $data['create_time']=date('Y-m-d H:i:s');
                $data['hash'] = $files->md5();
                $url = $fileDb->where(['hash'=>$data['hash']])->value('url');
                if($url){
                    $data['url']=$url;
                }else{
                    $url= $data['url'] ='/storage/'.$storage->putFile($this->topic, $files);
                    $fileDb->insert($data);
                }
            }

            return $url;
            

        } catch (\Throwable $e) {

            return_error(['info'=>$e->getMessage()]);

        }
    }

    public function setTopic($name)
    {
        $this->topic = $name;
    }
}